package com.xlong.component.rabbitmq;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xlong.BeanEntity.ResponseMsg;
import com.xlong.BeanEntity.TaskEntity;
import com.xlong.core.CommUtils;
import com.xlong.service.TaskService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@RabbitListener(queues = "DirectQueue")//监听的队列名称 DirectQueue
public class DirectReceiver {
	
	@Autowired
	private TaskService taskService;
	
	@RabbitHandler
    public void process(String taskstr) {
		log.info("接收到一条queue消息，开始处理...");
		JSONObject jsonObject = JSONObject.parseObject(taskstr);
		TaskEntity task = JSON.toJavaObject(jsonObject,TaskEntity.class);
		JSONObject json = task.getJson();
        //taskService = ManageSpringBeans.getBean(TaskService.class);
        ResponseMsg<JSONObject> responseMsg = taskService.getResult(json);
        
        log.info("已处理完消息，返回结果:{}", responseMsg);
        final DeferredResult<ResponseMsg<JSONObject>> result = CommUtils.SETTABLE_FUTURE_LOADING_CACHE.getIfPresent(task.getTaskId());
        if(result != null) {
        	result.setResult(responseMsg);
        }else {
        	log.error("缓存中无法指定DeferredResult:" + task.getTaskId());
        }
    }
	
}
